﻿mainModule.controller("articleEditCtrl", ["$scope", "$rootScope", "columnSvc", "notification", "pageState", "$routeParams", "articleSvc", "$location", "cache", "config", function ($scope, $rootScope, columnSvc, notification, pageState, $routeParams, articleSvc, $location, cache, config) {
    var articleID = $routeParams.articleID;
    var articleFindByIdUrl = "/api/articleapi/" + articleID;
    var mode = "edit";

    $scope.paging = { currentPage: 1, pageSize: config.paging.pageSize, linksSize: config.paging.linksSize };
    $scope.sorting = { column: "ID", ascending: true };        
    $scope.isColumnListVisible = false;    
            
    articleSvc.findById(articleID).then(function (response) {
        $scope.item = response.data;        
        $scope.list = response.data.Columns;    
        $scope.item.Columns = null;
        $scope.isColumnListVisible = ($scope.item.TypeID === 2);
        $rootScope.$broadcast("articleEdited", $scope.item);
    });

    $scope.cancel = function () {
        $location.path('/items/' + articleID);
    }

    $scope.save = function () {        
        articleSvc.edit($scope.item).then(function (response) {
            if (response.data.Success) {
                cache.remove(articleFindByIdUrl);
                $rootScope.$broadcast("articleEdited", $scope.item);
            }

            notification.notify(response.data);                
        });                
    }

    $scope.setColumnListVisibility = function () {
        $scope.isColumnListVisible = (parseInt($scope.item.TypeID) === 2);
    }    

    //column list functions
    function reloadList() {        
        articleSvc.findById(articleID).then(function (response) {           
            $scope.list = response.data.Columns;
            $scope.selectedIndex = -1;
        });
    }
                
    $scope.edit = function (index) {
        $scope.selectedIndex = index;
        var item = $scope.list[index];        
        $scope.$broadcast('itemClicked', item);
    }

    $scope.remove = function (index) {
        var item = $scope.list[index];
        columnSvc.remove(item.ID).then(function (response) {
            if (response.data.Success)
                $scope.list.splice(index, 1);

            cache.remove(articleFindByIdUrl);
            notification.notify(response.data);            
        });        
    }

    $scope.add = function() {
        $scope.$broadcast('itemAdding');
    }

    $scope.$on('listReload', function () {
        reloadList();
    });

    $scope.$on('resetIndex', function () {
        $scope.selectedIndex = -1;
    });
}]);




